/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import beans.Peliculas;
import beans.PeliculasFacadeLocal;
import beans.Series;
import beans.SeriesFacadeLocal;
import beans.Seriespeliculas;
import beans.SeriespeliculasFacadeLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author machine
 */
@WebServlet(name = "series", urlPatterns = {"/series"})
public class series extends HttpServlet {

    public HttpSession sesion = null;
    
    @EJB
    SeriesFacadeLocal miSessionSeries;
    @EJB
    SeriespeliculasFacadeLocal miSessionSerieVideos;
    @EJB
    PeliculasFacadeLocal miSessionPeliculas;
    
    String mensaje = "";
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
           
            
            
            
            sesion = request.getSession();
            if( sesion.getAttribute("usuario") != null || sesion.getAttribute("perfil") != null ){
                String perfilu = sesion.getAttribute("perfil").toString();
                if( perfilu != null ){
                    if( !perfilu.equals("2") ){
                        response.sendRedirect("index.jsp");
                        //request.getRequestDispatcher("index.jsp").forward(request, response); 
                    }
                }
                else{
                    response.sendRedirect("index.jsp");
                }
            }
            else{
                response.sendRedirect("index.jsp");
            }
                
            request.setAttribute("mensaje", mensaje);
            
            String htmlLogin = retornarDatosLoguin();
            
            request.setAttribute("loginAcceso", htmlLogin);
            
            String opcion = request.getParameter("opcion");
            
            request.setAttribute("opcion", opcion);
            
             switch ( Integer.parseInt(opcion) ) {
                
                
                default:  // Administrar Series
                        String misSeries = consultarSeries();
                        request.setAttribute("series", misSeries);
                        request.getRequestDispatcher("series.jsp?opcion=1").forward(request, response);    
                        break;
                
            }
            
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String name=null;
        if( request.getParameter("administrarserie") != null ){
            name = formularioAdminSerie(request.getParameter("administrarserie"));
            response.setContentType( "text/html; charset=iso-8859-1" );
            PrintWriter out = response.getWriter();
            out.println(name); 
        }
        else if( request.getParameter("eliminarserie") != null ){
            Boolean borro = eliminarSerie(request.getParameter("eliminarserie"));
            response.setContentType( "text/html; charset=iso-8859-1" );
            PrintWriter out = response.getWriter();
            if( borro ){
                 out.println("OK"); 
            }
            else{
                out.println("ERROR"); 
            }
        }
        else{
            processRequest(request, response);
        }
        
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String nuevaserie = request.getParameter("nuevaserie");
        String adicionaraserie = request.getParameter("adicionaraserie");
        
        if( nuevaserie != null ){
           
            if( nuevaserie.equals("1") ){
            
                String idserie = request.getParameter("idserie");
                if( idserie != null && !idserie.isEmpty() ){
                    Series editar = miSessionSeries.consultarSerie(idserie);
                    
                    String iden = request.getParameter("identificacion");
                    String nom = request.getParameter("nombre");

                    editar.setIdentificador(iden);
                    editar.setNombre(nom);

                    miSessionSeries.edit(editar);
                }
                else{
                    String iden = request.getParameter("identificacion");
                    String nom = request.getParameter("nombre");

                    Series s = new Series();

                    s.setIdentificador(iden);
                    s.setNombre(nom);

                    miSessionSeries.create(s);
                }
                
            }
        }
            
            
        // Adicionar video a Serie
        if( adicionaraserie != null ){
            if( adicionaraserie.equals("1") ){
                
                String peli = request.getParameter("peliculas");
                String idserie = request.getParameter("idserie");
                
                Seriespeliculas sp = new Seriespeliculas();
                Peliculas p = miSessionPeliculas.consultarPelicula(peli);
                Series s = miSessionSeries.consultarSerie(idserie);
                
                Boolean existe = false;
                
                List<Seriespeliculas> serpeli = miSessionSerieVideos.consultarVideos(idserie, peli);
                for( Seriespeliculas serp:serpeli ){
                    existe = true;
                }
                if( existe ){
                    mensaje =  "El video que intenta relacionar ya existe en esta serie.";
                }
                else{
                    sp.setIdpeliculas(p);
                    sp.setIdseries(s);
                    miSessionSerieVideos.create(sp);
                    mensaje = "Video relacionado existosamente.";
                }
                request.setAttribute("adicionaraseries", null);
                
            }
        }
        
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    
    
    
   private String retornarDatosLoguin(){
    
        String htmlLogin = "";

        
        // Si no se hainiciado Sesion
        if( sesion.getAttribute("usuario") == null ){
            htmlLogin = "<h3>Acceso de Usuario</h3>"
                    + "<br>"
                    + "  <ul class=\"list\">"
                    + "<li><a id=\"abrir\" href=\"javascript:initSession();\">Iniciar Session</a></li>"
                    + "<li><a id=\"abrir\" href=\"javascript:registerUser();\">Registrarse</a></li>"
                    +"</ul>  <br>";
        }
        else{
            htmlLogin = "<h3>Bienvenido "+ sesion.getAttribute("nusuario") +"</h3>"
                    + "<br>"
                    + "  <ul class=\"list\">"
                    + "<li><a id=\"abrir\" href=\"opciones?logout=1\">Cerrar Session</a></li>";
            
            if( sesion.getAttribute("perfil") != null ){ 
                String perfilu = sesion.getAttribute("perfil").toString();
                if( perfilu.equals("2") ){
                    htmlLogin += "<li><a id=\"abrir\" href=\"peliculas.jsp\">Administrar Peliculas</a></li>";
                    htmlLogin += "<li><a id=\"abrir\" href=\"series.jsp\">Administrar Series</a></li>";
                    htmlLogin += "<li><a id=\"abrir\" href=\"colecciones.jsp\">Administrar Colecciones</a></li>";
                }
            }
            
            htmlLogin += "</ul>  <br>";
        
        }
       return htmlLogin;
    }
    
   
   private String consultarSeries(){
       
       String htmlSeries = "";
       
       List<Series> misSeries = miSessionSeries.findAll();
       
       if( misSeries != null ){
           
        htmlSeries += " <table width='70%' style='border: orange 1px solid; background-color:#FAFAFA;' > ";   
        htmlSeries += " <tr> ";   
        htmlSeries += " <th style='border: orange 1px solid;'>Código</th> ";   
        htmlSeries += " <th style='border: orange 1px solid;'>Nombre</th> ";   
        htmlSeries += " <th style='border: orange 1px solid;'>Cantidad Videos</th> ";   
        htmlSeries += " <th style='border: orange 1px solid;'>Editar</th> ";   
        htmlSeries += " <th style='border: orange 1px solid;'>Eliminar</th> ";   
        htmlSeries += " </tr> ";   
           
        
        Integer cantidad = 0;
        for( Series c:misSeries ){

            cantidad = 0;
            cantidad = miSessionSerieVideos.consultarCantidad( c.getIdseries() );
            
            htmlSeries += " <tr> ";   
            htmlSeries += " <td style='border: orange 1px solid;'>"+ c.getIdentificador() +"</td> ";   
            htmlSeries += " <td style='border: orange 1px solid;'>"+ c.getNombre() +"</td> ";   
            htmlSeries += " <td style='border: orange 1px solid; cursor:pointer;' onclick = 'adminSerie("+c.getIdseries()+");'><center><a style='color:#000000;' href='javascript:;' data-tool=\"Administrar esta Serie\" class=\"tooltip animate\" >"+cantidad+"</a></center></center></td> ";   
            htmlSeries += " <td style='border: orange 1px solid;'><center><a style='color:#000000;' href='javascript:modificarSerie(\""+c.getIdseries()+"\",\""+c.getNombre()+"\",\""+c.getIdentificador()+"\");'>Editar</a></center></td> ";   
            htmlSeries += " <td style='border: orange 1px solid;'><center><a style='color:#000000;' href='javascript:eliminarSerie(\""+c.getIdseries()+"\",\""+c.getNombre()+"\",\""+c.getIdentificador()+"\");'>Eliminar</a></center></td> ";   
            htmlSeries += " </tr> ";   

            
        }
        
        htmlSeries += " </table> ";   
       }
       
       return htmlSeries;
       
   }

    private String formularioAdminSerie( String idserie ) {
        
        String formulario = "";
        Integer cant = 0;
        Series nombreSerie = miSessionSeries.consultarSerie(idserie);
        List<Seriespeliculas> miserpeli = miSessionSerieVideos.consultarVideos( idserie, null );
        
        formulario += "<br><form method=\"post\" action=\"series?opcion=0\">"
                    + "<table width=\"70%\" style=\"border: orange 1px solid; background-color:#FAFAFA;\">";
        formulario += "<tr>";
        formulario += "<th style='border: orange 1px solid;'>Videos asociados a Serie:  "+nombreSerie.getNombre()+"</th>";
        formulario += "</tr>";
        
        for ( Seriespeliculas c:miserpeli ){
            formulario += "<tr>";
            formulario += "<td style='border: orange 1px solid;'><span style=\"float:left;\">"+c.getIdpeliculas().getTitulo()+"</span>"
                    + "<span style=\"float:right;\"><a href=\"javascript:eliminarSerie("+c.getIdseriespeliculas()+", '"+c.getIdpeliculas().getTitulo()+"', '"+c.getIdpeliculas().getIdentificador()+"')\" data-tool=\"Eliminar relacion\" class=\"tooltip animate\"><img src=\"images/delete.jpg\" width=\"20px\"></a></span></td>";
            formulario += "</tr>";
            cant++;
        }
        
        if( cant == 0 ){
            formulario += "<tr><td style='border: orange 1px solid;'>Esta Serie no tiene asociado nungun video aun.</tr></tr>";
        }
        
        String selectPeliculas = "";
        List<Peliculas> pelis = miSessionPeliculas.findAll();
        
        if( pelis != null ){
            selectPeliculas += "<select name='peliculas'>";
            for( Peliculas p:pelis ){
                if( p.getIdcategorias().getIdcategorias() >= 1000 )
                selectPeliculas += "<option value=\""+p.getIdpeliculas()+"\"> "+ p.getTitulo() +" </option>";
            }
            selectPeliculas += "</select>";
        }
        
        formulario += "<tr><td style='text-align:center; vertical-align:center;'> "+ selectPeliculas +" &nbsp;&nbsp;&nbsp;&nbsp;";
        formulario += "<a  data-tool=\"Adicionar video a "+nombreSerie.getNombre()+"\" class=\"tooltip animate\"><input type=\"image\" src=\"images/add.png\" width=\"20px\"></a> </td></tr>";
        
        formulario += "</table><br>"
                    + "<input type=\"hidden\" name=\"idserie\" id=\"idserie\" value=\""+nombreSerie.getIdseries()+"\">"
                    + "<input type=\"hidden\" name=\"adicionaraserie\" id=\"adicionaraserie\" value=\"1\">"
                + "</form>";
        
        return formulario;
    }

    private Boolean eliminarSerie(String idSerie) {
        
        Series misrie = miSessionSeries.consultarSerie(idSerie);
        
        miSessionSeries.remove(misrie);
        
        return true;
        
    }
    
    
    
}
